package com.zc.zby.fwone;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.wang.avi.AVLoadingIndicatorView;
import com.zxy.tiny.Tiny;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.zc.zby.fwone.FileProveiderUtils.getFileSize;
import static com.zc.zby.fwone.FileProveiderUtils.getPath;
import static com.zc.zby.fwone.FileProveiderUtils.getUriForFile;

public class MainActivity extends AppCompatActivity implements MyWebChromeClient.WebCall {

    private String HomeUrl = "http://37.chungkeedessert.com.cn/wap";
    private String mUrl;
    private ValueCallback<Uri> mUploadMessage;// 表单的数据信息
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private final static int FILECHOOSER_RESULTCODE = 1;// 表单的结果回调</span>
    private Uri imageUri;
    private String mFilePath;
    private String mFileName;
    private File file;
    private Uri[] results;
    private AVLoadingIndicatorView avLoadingIndicatorView;
    private WebView webView;
    private long exitTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        webView = findViewById(R.id.webView);
        avLoadingIndicatorView = findViewById(R.id.avi);
        avLoadingIndicatorView.show();
        FileProveiderUtils.init();
        mFilePath = FileProveiderUtils.getFileDir() + File.separator;
        //支持javascript
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setDatabaseEnabled(true);
        // 设置可以访问文件
        webView.getSettings().setAllowFileAccess(true);
        // webSettings.setSupportZoom(true);
        //自适应屏幕
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.loadUrl(HomeUrl);
        webView.setWebViewClient(new myWebViewClient());
        MyWebChromeClient chromeClient = new MyWebChromeClient();
        chromeClient.setWebCall(this);
        webView.setWebChromeClient(chromeClient);
    }

    @Override
    public void fileChose(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        take();
    }

    @Override
    public void fileChose5(ValueCallback<Uri[]> uploadMsg) {
        mUploadCallbackAboveL = uploadMsg;
        take();
    }

    /**
     * 选择照片或拍照后回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (mUploadMessage != null) {
                if (result == null) {
                    Log.e("--onActivity imageUri", imageUri + "");
                    mUploadMessage.onReceiveValue(imageUri);
                    mUploadMessage = null;
                } else {
                    mUploadMessage.onReceiveValue(result);
                    mUploadMessage = null;
                }
            }
        }
    }

    @SuppressWarnings("null")
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != FILECHOOSER_RESULTCODE
                || mUploadCallbackAboveL == null) {
            return;
        }
        results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
                // 拍照后
                Log.e("--AboveL data == null", imageUri.toString());
                results = new Uri[]{imageUri};
            } else {
                // 相册选择后
                Log.e("--AboveL", "data != null");
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();

                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                        LogUtil.e("--AboveL dataString != null " + i + " " + results[i]);
                    }
                }

                if (dataString != null) {
                    LogUtil.e("--AboveL dataString != null " + dataString);
                    results = new Uri[]{Uri.parse(dataString)};
                }
                // 将相册中图片的路径转化为可用路径 content://com.zc.zby.androidoa.fileprovider -> /storage/emulated/0/Android/data/com.zc.zby.androidoa
                String path = getPath(MainActivity.this, results[0]);
                file = new File(path);
            }
        }
        // 进行图片压缩
        Tiny.FileCompressOptions options = new Tiny.FileCompressOptions();
        LogUtil.e("--file path " + file.getPath());
        try {
            LogUtil.e("--file size " + getFileSize(file));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Tiny.getInstance().source(file).asFile().withOptions(options).compress(new com.zxy.tiny.callback.FileCallback() {
            @Override
            public void callback(boolean isSuccess, String outfile, Throwable t) {
                LogUtil.e("--outFile " + outfile);
                try {
                    LogUtil.e("--press file size " + getFileSize(new File(outfile)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (results != null) {
                    results[0] = getUriForFile(MainActivity.this, new File(outfile));
                    Log.e("--results[0]", results[0].toString());
                    mUploadCallbackAboveL.onReceiveValue(results);
                    mUploadCallbackAboveL = null;
                    //content://com.honjane.providerdemo.fileprovider/honjane/storage/emulated/0/honjane/files/1517552706827.jpg
                } else {
                    imageUri = getUriForFile(MainActivity.this, new File(outfile));
                    results = new Uri[]{imageUri};
                    LogUtil.e("--results " + results[0]);
                    mUploadCallbackAboveL.onReceiveValue(results);
                    mUploadCallbackAboveL = null;
                }
            }
        });
        return;
    }

    /**
     * 调用手机中能拍照和获取文件的应用
     */
    private void take() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File path = new File(mFilePath);
            if (!path.exists()) {
                path.mkdirs();
            }
            mFileName = System.currentTimeMillis() + ".jpg";
            file = new File(path, mFileName);
            if (file.exists()) {
                file.delete();
            }
            imageUri = getUriForFile(this, file);
        } else {
            Log.e("main", "sdcard not exists");
        }

        Log.e("--imageUri", imageUri.toString());
        final List<Intent> cameraIntents = new ArrayList<Intent>();
        final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        final PackageManager packageManager = getPackageManager();
        final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
        for (ResolveInfo res : listCam) {
            final String packageName = res.activityInfo.packageName;
            final Intent i = new Intent(captureIntent);
            i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            i.setPackage(packageName);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
            i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
            i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            cameraIntents.add(i);
            Log.e("packageName", res.activityInfo.packageName.toString());
            Log.e("name", res.activityInfo.name.toString());
        }
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
    }

    class myWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub
            //此处为加载URL，但是有时候与H5交互的时候使用JavaScriptinterface时没有作用，具体为什么目前还没有研究清楚，
            //但是为了实现交互调用android的方法我们可以与H5约定好URL的格式内容，判断是否为约定好的URL，是则调用本来要调用的本地方法，不是则加载页面即可。
            LogUtil.e("shouldOverrideUrlLoading: " + url);
            return false;
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
            LogUtil.e("onReceivedSslError");
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            LogUtil.e("onPageStarted: " + url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            LogUtil.e("onPageFinished: " + url);
            mUrl = url;
            avLoadingIndicatorView.setVisibility(View.GONE);
            avLoadingIndicatorView.hide();
        }
    }

    /**
     * 监听back键处理DrawerLayout和SearchView
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //#init #deals #transfer #login
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            String substring[] = mUrl.split("#");
            String end = "#" + substring[substring.length - 1];
            if (end.equals("#init") || end.equals("#deals") || end.equals("#transfer") || end.equals("#login")) {
                exitApp();
            } else {
                if (webView != null && webView.canGoBack()) {
                    webView.goBack();
                    return true;
                } else {
                    exitApp();
                }
            }
        }
        return true;
    }

    /**
     * 双击退出App
     */
    private void exitApp() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }
}
